import { login, getInfo } from '@/api/user'
import { getCustomerInfo } from '@/api/customer'
import { getToken, setToken, removeToken, getUser, setUser, removeUser } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: getUser(),
    roles: []
    // avatar: ''
  }
}

const getCustomerType = async(name) => {
  const res = await getCustomerInfo(name)
  return res.data.data
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_ROLE: (state, roles) => {
    state.roles = roles
  },
  SET_USERTYPE: (state, type) => {
    state.type = type
  },
  SET_DISCOUNT: (state, discount) => {
    state.discount = discount
  }
  // SET_AVATAR: (state, avatar) => {
  //   state.avatar = avatar
  // }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ username: username.trim(), password: password }).then(response => {
        const { data } = response
        commit('SET_TOKEN', data.data.token)
        commit('SET_NAME', data.data.username)
        setToken(data.data.token)
        setUser(data.data.username)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // get user info
  getInfo(store) {
    return new Promise((resolve, reject) => {
      getInfo(store.state).then(response => {
        const { data } = response.data
        if (!data) {
          return reject('Verification failed, please Login again.')
        }
        const { username, role } = data
        if (role === 'normal') {
          getCustomerType(username).then(res => {
            store.commit('SET_USERTYPE', res.userType)
            store.commit('SET_DISCOUNT', res.discount)
          })
        }
        const roles = role.split(',')
        if (!roles || roles.length <= 0) {
          return reject('getInfo: roles must be a non-null array!')
        }
        store.commit('SET_NAME', username)
        store.commit('SET_ROLE', roles)

        // commit('SET_AVATAR', avatar)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit }) {
    return new Promise((resolve, reject) => {
      // logout().then(() => {
      removeToken() // must remove  token  first
      removeUser()
      resetRouter()
      commit('RESET_STATE')
      resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      removeUser()
      commit('RESET_STATE')
      resolve()
    })
  },
  changeUserType({ commit }, type) {
    return new Promise((resolve, reject) => {
      commit('SET_USERTYPE', type)
    })
  },
  changeUserDiscount({ commit }, discount) {
    return new Promise((resolve, reject) => {
      commit('SET_DISCOUNT', discount)
    })
  },
  // dynamically modify permissions
  // 变更角色时动态更新路由表，这个也先复制过来
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'
    commit('SET_TOKEN', token)
    setToken(token)
    const { roles } = await dispatch('getInfo')
    resetRouter()
    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

